package com.xbongbong.saas.model.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.model.PaasFormDataEsModel;
import com.xbongbong.paas.elasticsearch.pojo.XbbAggregatedPage;
import com.xbongbong.paas.elasticsearch.pojo.dto.DeleteDTO;
import com.xbongbong.paas.elasticsearch.pojo.dto.InsertDTO;
import com.xbongbong.paas.elasticsearch.util.EsUtil;
import com.xbongbong.paas.elasticsearch.util.XbbElasticsearchRestTemplate;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.pojo.MultiUnitPricePoJo;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.wrap.EnableApiCallBack;
import com.xbongbong.paas.util.DataUtil;
import com.xbongbong.pro.businessdata.pojo.dto.FormatExplainDTO;
import com.xbongbong.pro.constant.BusinessConstant;
import com.xbongbong.pro.constant.ElasticConstant;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.pro.enums.ApiCallBackEnum;
import com.xbongbong.pro.formdata.pojo.dto.SaasAnalysisDataDTO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.ProductConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.dao.QuotationDao;
import com.xbongbong.saas.domain.entity.QuotationProductEntity;
import com.xbongbong.saas.domain.entity.ext.ProductEntityExt;
import com.xbongbong.saas.domain.entity.ext.QuotationEntityExt;
import com.xbongbong.saas.enums.OperatePageEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.RelativeProductEnum;
import com.xbongbong.saas.enums.SelectProductEnum;
import com.xbongbong.saas.enums.UpdateDataTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.enums.business.QuotationEnum;
import com.xbongbong.saas.enums.product.QuotationProductEnum;
import com.xbongbong.saas.help.ExplainHelp;
import com.xbongbong.saas.help.SaasFormHelp;
import com.xbongbong.saas.help.ShowFormatHelp;
import com.xbongbong.saas.model.PaasFormSubDataModel;
import com.xbongbong.saas.model.ProductModel;
import com.xbongbong.saas.model.ProductUnitPriceModel;
import com.xbongbong.saas.model.QuotationModel;
import com.xbongbong.saas.model.QuotationProductModel;
import com.xbongbong.saas.model.QuotationSubDataModel;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import org.elasticsearch.action.search.SearchRequest;
import com.xbongbong.saas.util.StandardizeDataUtil;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import static com.xbongbong.saas.enums.RelativeProductEnum.MEMO;
import static com.xbongbong.saas.enums.RelativeProductEnum.NUM;
import static com.xbongbong.saas.enums.RelativeProductEnum.SALE_DISCOUNT;
import static com.xbongbong.saas.toolbox.help.FastJsonHelper.getDoubleOrDefaultFromFormData;
import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

/**
 * @author long.rao
 * @version v1.0
 * @date 2019/8/12 17:23
 * @since v1.0
 */
@Service("quotationModel")
public class QuotationModelImpl implements QuotationModel {

    @Resource
    private ExplainHelp explainHelp;
    @Resource
    private QuotationDao quotationDao;
    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private PaasFormDataEsModel paasFormDataEsModel;
    @Resource
    private PaasFormSubDataModel paasFormSubDataModel;
    @Resource
    private QuotationSubDataModel quotationSubDataModel;
    @Resource
    private ShowFormatHelp showFormatHelp;
    @Resource
    private ProductModel productModel;
    @Resource
    private ProductUnitPriceModel productUnitPriceModel;
    @Resource
    private QuotationProductModel quotationProductModel;
    @Resource
    private SaasFormHelp saasFormHelp;
    @Resource
    private XbbElasticsearchRestTemplate xbbElasticsearchRestTemplate;

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.QUOTATION, operateTypeEnum = OperateTypeEnum.NEW)
    public Integer insert(QuotationEntityExt entity) throws XbbException {
        long now = DateTimeUtil.getInt();
        entity.setAddTime(now);
        entity.setUpdateTime(now);

        paasFormSubDataModel.transferSubForm(entity, IndexTypeEnum.IDX_SAAS_QUOTATION_SUB);
        StandardizeDataUtil.standardizeNotString(entity);
        Integer success = quotationDao.insert(entity);
        PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
        BeanUtil.copyProperties(entity, paasFormDataEntity);
        InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_QUOTATION);
        paasEsModel.insert(insertDTO);

        paasFormSubDataModel.insertSubFormData(entity, IndexTypeEnum.IDX_SAAS_QUOTATION_SUB);
        return success;
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.QUOTATION, operateTypeEnum = OperateTypeEnum.EDIT)
    public Integer update(QuotationEntityExt entity) throws XbbException {
        long now = DateTimeUtil.getInt();
        entity.setUpdateTime(now);

        paasFormSubDataModel.transferSubForm(entity, IndexTypeEnum.IDX_SAAS_QUOTATION_SUB);
        StandardizeDataUtil.standardizeNotString(entity);
        Integer success = quotationDao.update(entity);
        Integer updateSub = paasFormSubDataModel.updateSubFormData(entity, IndexTypeEnum.IDX_SAAS_QUOTATION_SUB);
        if (Objects.equals(1, success) || Objects.equals(1, updateSub)) {
            // 更新时间
            success = quotationDao.updateTime(now + 1, entity.getId(), entity.getCorpid());
            // 更新es
            PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
            BeanUtil.copyProperties(entity, paasFormDataEntity, false);
            InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_QUOTATION);
            insertDTO.getSource().remove("creatorId");
            paasEsModel.update(insertDTO);
        }
        if (Objects.nonNull(entity.getSubFormData()) && !entity.getSubFormData().isEmpty()) {
            entity.getData().putAll(entity.getSubFormData());
        }

        return success;
    }

    @Override
    public List<QuotationEntityExt> findEntitys(Map<String, Object> param) {
        List<QuotationEntityExt> entitys = quotationDao.findEntitys(param);
        Object corpid = param.get(ParameterConstant.CORPID);
        if (Objects.nonNull(corpid)) {
            paasFormSubDataModel.findSubEntity(corpid.toString(), entitys, IndexTypeEnum.IDX_SAAS_QUOTATION_SUB);
        }
        return entitys;
    }

    @Override
    public Integer getEntitysCount(Map<String, Object> param) {
        return quotationDao.getEntitysCount(param);
    }

    @Override
    public QuotationEntityExt getByKey(Long key, String corpid) {
        QuotationEntityExt quotationDaoByKey = quotationDao.getByKey(key, corpid);
        paasFormSubDataModel.findSubEntity(corpid, Collections.singletonList(quotationDaoByKey), IndexTypeEnum.IDX_SAAS_QUOTATION_SUB);
        return quotationDaoByKey;
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.QUOTATION, operateTypeEnum = OperateTypeEnum.DELETE, isBatch = true)
    public Integer deleteBatch(List<Long> deleteIdIn, String corpid) throws XbbException{
        Integer integer = quotationDao.deleteBatch(deleteIdIn, corpid);
        paasEsModel.deleteBatch(deleteIdIn, corpid, DelEnum.DELETE.getDel(), IndexTypeEnum.IDX_SAAS_QUOTATION);
        paasFormSubDataModel.deleteBatchByDataId(deleteIdIn, corpid, IndexTypeEnum.IDX_SAAS_QUOTATION_SUB, DelEnum.DELETE_SUBFORM);
        return integer;
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.QUOTATION, operateTypeEnum = OperateTypeEnum.DELETE)
    public Integer deleteByKey(Long key,String corpid) throws XbbException{
        DeleteDTO deleteDTO = new DeleteDTO();
        deleteDTO.setEsId(corpid+"_"+key);
        deleteDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_QUOTATION);
        paasEsModel.delete(deleteDTO);
        Integer integer = quotationDao.deleteByKey(key, corpid);

        paasFormSubDataModel.deleteByDataId(key, corpid, IndexTypeEnum.IDX_SAAS_QUOTATION_SUB);

        return integer;
    }

    @Override
    public List<QuotationEntityExt> getQuotationByDeadlineTime(String corpid, Long startDeadlineTime, Long endDeadlineTime) {
        List<QuotationEntityExt> quotationEntityExts = quotationDao.getQuotationByDeadlineTime(corpid, startDeadlineTime, endDeadlineTime);
        paasFormSubDataModel.findSubEntity(corpid, quotationEntityExts, IndexTypeEnum.IDX_SAAS_QUOTATION_SUB);
        return quotationEntityExts;
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.QUOTATION, operateTypeEnum = OperateTypeEnum.EDIT, isBatch = true)
    public Integer updateBatch(List<UpdateDataEntity> updateList, String corpid) throws XbbException {
        //1. 先拿到子表单数据
        List<UpdateDataEntity> subList = DataUtil.getUpdateSubDataList(updateList);
        // 2. 主表删掉子表单数据
        DataUtil.removeSubDataInData(updateList);
        Integer integer = 0;
        if (CollectionsUtil.isNotEmpty(updateList)) {
            StandardizeDataUtil.standardizeList(updateList);
            integer = quotationDao.updateBatch(updateList, corpid);
            paasEsModel.updateBatchMuchField(updateList, IndexTypeEnum.IDX_SAAS_QUOTATION);
        }
        if (!subList.isEmpty()) {
            quotationSubDataModel.updateBatch(subList, corpid);
        }
        return integer;
    }

    /**
     * 数据还原
     * @param dataIdList
     * @param corpid
     * @param del
     * @throws XbbException
     */
    @Override
    public Integer restoreBatch(List<Long> dataIdList, String corpid, Integer del) throws XbbException {
        Integer count = quotationDao.restoreBatch(dataIdList, corpid, del);
        updateBatchDel(dataIdList, corpid, del);

        paasFormSubDataModel.restoreBatch(dataIdList, corpid, IndexTypeEnum.IDX_SAAS_QUOTATION_SUB);
        return count;
    }

    private void updateBatchDel(List<Long> dataIdList, String corpid, Integer del) throws XbbException{
        Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put("del", del);
        map.put("updateTime", DateTimeUtil.getInt());
        paasFormDataEsModel.updateBatch(dataIdList, corpid, map, IndexTypeEnum.IDX_SAAS_QUOTATION);
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.QUOTATION, operateTypeEnum = OperateTypeEnum.EDIT, isBatch = true)
    public Integer updateBatch(List<UpdateDataEntity> updateList, String corpid, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException {
        //1. 先拿到子表单数据
        List<UpdateDataEntity> subList = DataUtil.getUpdateSubDataList(updateList);
        // 2. 主表删掉子表单数据
        DataUtil.removeSubDataInData(updateList);
        Integer integer = 0;
        if (CollectionsUtil.isNotEmpty(updateList)) {
            StandardizeDataUtil.standardizeList(updateList);
            integer = quotationDao.updateBatch(updateList, corpid);
            paasEsModel.updateBatchMuchField(updateList, IndexTypeEnum.IDX_SAAS_QUOTATION, refreshPolicy);
        }
        if (!subList.isEmpty()) {
            quotationSubDataModel.updateBatch(subList, corpid);
        }
        return integer;
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.QUOTATION, operateTypeEnum = OperateTypeEnum.EDIT, isBatch = true)
    public Integer updateBatch(List<UpdateDataEntity> updateList, String corpid, boolean needThrow) throws XbbException {
        Integer integer = quotationDao.updateBatch(updateList, corpid);
        paasEsModel.updateBatchMuchField(updateList, IndexTypeEnum.IDX_SAAS_QUOTATION, needThrow);
        return integer;
    }


    @Override
    public List<QuotationEntityExt> findEntitysWithoutSub(Map<String, Object> param) {
        return quotationDao.findEntitys(param);
    }

    @Override
    public void formatUpdateExplain(FormatExplainDTO formatExplainDTO) throws XbbException {
        List<FieldAttrEntity> entities = formatExplainDTO.getExplainList();
        String corpid = formatExplainDTO.getCorpid();
        for (FieldAttrEntity fieldAttrEntity : entities) {
            String attr = fieldAttrEntity.getAttr();
            if (Objects.equals(attr, QuotationEnum.PRODUCT.getAttr())) {
                explainHelp.formatSelectProductExplains(fieldAttrEntity, XbbRefTypeEnum.QUOTATION, corpid, OperatePageEnum.NEW.getCode(), false);
                fieldAttrEntity.setSupportScanning(BasicConstant.ONE);
            } else if (Objects.equals(attr, QuotationEnum.PRODUCT_TOTAL.getAttr())) {
                fieldAttrEntity.setEditable(BasicConstant.ZERO);
            } else if (Objects.equals(attr, QuotationEnum.QUOTATION_NO.getAttr())) {
                fieldAttrEntity.setEditable(BasicConstant.ZERO);
            } else if (Objects.equals(attr, QuotationEnum.CUSTOMER_ID.getAttr())) {
                fieldAttrEntity.setEditable(BasicConstant.ZERO);
            } else if (Objects.equals(attr, QuotationEnum.OPPORTUNITY_ID.getAttr())) {
                fieldAttrEntity.setEditable(BasicConstant.ZERO);
            }
        }
    }

    @Override
    public void formatData(SaasAnalysisDataDTO formDataUpdateGetDTO, JSONObject result) throws XbbException {
        showFormatHelp.formatLinkBusiness4ShowBySource(result, QuotationEnum.CUSTOMER_ID.getAttr(), QuotationEnum.CUSTOMER_NAME.getAttr(), QuotationEnum.CUSTOMER_ID.getFieldType(), XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), XbbRefTypeEnum.SALES_OPPORTUNITY.getCode(), formDataUpdateGetDTO.getCorpid());
        showFormatHelp.formatLinkBusiness4Show(result, QuotationEnum.CONTACT_ID.getAttr(), QuotationEnum.CONTACT_NAME.getAttr(), QuotationEnum.CONTACT_NAME.getFieldType());
        showFormatHelp.formatLinkBusiness4Show(result, QuotationEnum.OPPORTUNITY_ID.getAttr(), QuotationEnum.OPPORTUNITY_NAME.getAttr(), QuotationEnum.OPPORTUNITY_NAME.getFieldType());
        // 格式化关联产品
        //formatProduct4Show(result, formDataUpdateGetDTO);
    }

    @Override
    public void getProductList(String corpid, List<QuotationProductEntity> quoProductList, JSONArray productArray, Map<Long, ProductEntityExt> productMap) throws XbbException {
        Integer sort = 0;
        for (int i = 0; i < productArray.size(); i++) {
            JSONObject productArrayJSONObject = productArray.getJSONObject(i);
            sort++;
            // 页面传入的产品id
            Long pageProductId = FastJsonHelper.getLongOrDefaultFromFormData(productArrayJSONObject, StringConstant.SAAS_LINK_BUSINESS_ID, 0L);
            // 产品数量
            Double productNum = getDoubleOrDefaultFromFormData(productArrayJSONObject, NUM.getSaasAttr(), 0D);
            // 折扣
            Double discount = getDoubleOrDefaultFromFormData(productArrayJSONObject, SALE_DISCOUNT.getSaasAttr(), 0D);
            // 售价
            Double price = getDoubleOrDefaultFromFormData(productArrayJSONObject, RelativeProductEnum.SALE_PRODUCT_PRICE.getSaasAttr(), 0D);
            // 备注
            String memo = FastJsonHelper.getStringOrDefaultFromFormData(productArrayJSONObject, MEMO.getSaasAttr(), "");
            // 产品成本
            Double cost = getDoubleOrDefaultFromFormData(productArrayJSONObject, "estimateCost", 0D);
            if (productMap.containsKey(pageProductId)) {
                ProductEntityExt product = productMap.get(pageProductId);
                JSONObject productObject = product.getData();
                String specification = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.SPECIFICATION_LINK_TEXT.getAttr(), "");
                String productName = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.NAME.getAttr(), "");
                String productNo = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.PRODUCT_NO.getAttr(), "");
                String unit = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.UNIT.getAttr(), "");
                String barcode = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.BARCODE.getAttr(), "");
                Long parentId = FastJsonHelper.getLongOrDefaultFromFormData(productObject, ProductEnum.PARENT_ID.getAttr(), 0L);
                QuotationProductEntity productEntity = new QuotationProductEntity();
                productEntity.setBarcode(barcode);
                productEntity.setProductUnit(unit);
                productEntity.setCorpid(corpid);
                productEntity.setParentId(parentId);
                productEntity.setProductId(pageProductId);
                productEntity.setParentId(parentId);
                productEntity.setProductNum(productNum);
                productEntity.setProductName(productName);
                productEntity.setProductNo(productNo);
                productEntity.setSpecification(specification);
                productEntity.setDiscount(discount);
                productEntity.setPrice(price);
                productEntity.setCost(cost);
                productEntity.setMemo(memo);
                productEntity.setSort(sort);
                /*JSONObject jsonObject = new JSONObject();
                jsonObject.put(QuotationProductEnum.PRODUCT.getAttr(), pageProductId);
                jsonObject.put(QuotationProductEnum.UNIT.getAttr(), unit);
                jsonObject.put(QuotationProductEnum.NUM.getAttr(), productNum);
                jsonObject.put(QuotationProductEnum.DISCOUNT.getAttr(), discount);
                jsonObject.put(QuotationProductEnum.SELLING_PRICE.getAttr(), price);
                jsonObject.put(QuotationProductEnum.SUBTOTAL.getAttr(), price * productNum);
                jsonObject.put(QuotationProductEnum.MEMO.getAttr(), memo);
                jsonObject.put(QuotationProductEnum.PRICE.getAttr(), price);
                productEntity.setData(jsonObject);*/
                quoProductList.add(productEntity);
            }
        }
    }

    @Override
    public JSONObject formatSingleProduct(QuotationProductEntity quotationProductEntity) {
        JSONObject json = quotationProductEntity.getData();
        showFormatHelp.approvalSetBusinessUnit(json, quotationProductEntity);
        if (Objects.isNull(json) || json.isEmpty()){
            json = new JSONObject();
            for (QuotationProductEnum quotationProductEnum : QuotationProductEnum.values()){
                String attr = quotationProductEnum.getAttr();
                switch (quotationProductEnum){
                    case PRODUCT:
                        json.put(attr,quotationProductEntity.getProductId());
                        break;
                    case DISCOUNT:
                        json.put(attr,quotationProductEntity.getDiscount());
                        break;
                    case PRICE:
                        json.put(attr, 0D);
                        break;
                    case SELLING_PRICE:
                        json.put(attr,quotationProductEntity.getPrice());
                        break;
                    case NUM:
                        json.put(attr,quotationProductEntity.getProductNum());
                        break;
                    case MEMO:
                        json.put(attr,quotationProductEntity.getMemo());
                        break;
                    case SUBTOTAL:
                        json.put(attr,quotationProductEntity.getPrice() * quotationProductEntity.getProductNum());
                        break;
                    case UNIT:
                        json.put(attr, quotationProductEntity.getProductUnit());
                        break;
                    default:
                        break;
                }
            }
        }
        if (Objects.nonNull(quotationProductEntity.getProductPriceArr())) {
            json.put(ProductConstant.PRODUCT_PRICE, quotationProductEntity.getProductPriceArr());
        }
        return json;
    }

    @Override
    public void formatProduct4Show3(List<QuotationProductEntity> quotationProductEntityList, JSONObject productData, UpdateDataTypeEnum updateDataTypeEnum, String corpid) throws XbbException {
        List<Long> productIds = new ArrayList<>();
        for (QuotationProductEntity quotationProductEntity : quotationProductEntityList){
            if (Objects.nonNull(quotationProductEntity.getProductId()) && !Objects.equals(quotationProductEntity.getProductId(), 0L)) {
                productIds.add(quotationProductEntity.getProductId());
            } else if (Objects.nonNull(quotationProductEntity.getData())){
                productIds.add(quotationProductEntity.getData().getLong(SelectProductEnum.PRODUCT.getAttr()));
            }
        }
        Map<Long, ProductEntityExt> productMap = productModel.getProductMapByIds(corpid, productIds, DelEnum.NORMAL.getDel(), Arrays.asList(StringConstant.SAAS_LINK_BUSINESS_ID, ProductEnum.getAttrConnectData(ProductEnum.STOCK), ProductEnum.getEsAttr4Keyword(ProductEnum.NAME), ProductEnum.getAttrConnectData(ProductEnum.ONLINE), ProductEnum.getAttrConnectData(ProductEnum.ENABLE_MULTI_UNIT), ProductEnum.getAttrConnectData(ProductEnum.PRICE)));
        Set<Long> multiUnitProductIds = new HashSet<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        productMap.forEach((key,value)->{
            if (Objects.equals(value.getData().getInteger(ProductEnum.ENABLE_MULTI_UNIT.getAttr()), 1)) {
                multiUnitProductIds.add(key);
            }
        });
        Map<Long, List<MultiUnitPricePoJo>> priceMap = productUnitPriceModel.getPriceMapByProductIdSet(corpid, multiUnitProductIds);
        JSONArray productArray = new JSONArray();
        Iterator iterator = quotationProductEntityList.iterator();
        // fix:修复下架多个产品后也只显示一个，将hashset改为arraylist
        List<String> offlinedProducts = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        while (iterator.hasNext()){
            QuotationProductEntity quotationProductEntity = (QuotationProductEntity)iterator.next();
            JSONObject quoProductData = quotationProductEntity.getData();
            Long productId = -1L;
            if (Objects.nonNull(quoProductData)){
                productId = quoProductData.getLong(QuotationProductEnum.PRODUCT.getAttr());
            } else {
                productId = quotationProductEntity.getProductId();
            }
            ProductEntityExt productEntityExt = productMap.get(productId);
            if (Objects.isNull(productEntityExt)) {
                continue;
            }
            if (Objects.nonNull(priceMap.get(productId))) {
                quotationProductEntity.setProductPriceArr(JSONArray.parseArray(JSONArray.toJSONString(priceMap.get(productId))));
            }
            JSONObject proData = productEntityExt.getData();
            if(Objects.equals(updateDataTypeEnum,UpdateDataTypeEnum.COPY)){
                // 下架产品剔除掉，fix:将list中原本传入表单名字改为产品名字，表单名字直接外面拿
                Integer online = proData.getInteger(ProductEnum.ONLINE.getAttr());
                String name = proData.getString(ProductEnum.NAME.getAttr());
                if (!Objects.equals(1,online)){
                    offlinedProducts.add(name);
                    continue;
                }
            }
            quotationProductEntity.setUnitPrice(Objects.isNull(productEntityExt.getData().getDouble(ProductEnum.PRICE.getAttr())) ? 0D : productEntityExt.getData().getDouble(ProductEnum.PRICE.getAttr()));
            JSONObject json = formatSingleProduct(quotationProductEntity);
            if (updateDataTypeEnum.isUpdate() || updateDataTypeEnum.isDetail()){
                json.put(BusinessConstant.PRODUCT_SUB_ID,quotationProductEntity.getId());
                if (Objects.isNull(quotationProductEntity.getId())) {
                    json.put(BusinessConstant.PRODUCT_SUB_ID,0);
                }
            }else {
                json.put(BusinessConstant.PRODUCT_SUB_ID,0);
            }
            if (updateDataTypeEnum.isLinkAdd()){
                json.put(SelectProductEnum.UNIT.getAttr(), saasFormHelp.formatUnit(quotationProductEntity.getCorpid(),quotationProductEntity.getProductUnit()));
                json.put(BusinessConstant.RELY_PRODUCT_SUB_ID, quotationProductEntity.getId());
            }
            json.put("refId",quotationProductEntity.getId());
            productArray.add(json);
        }
        productData.put(QuotationEnum.PRODUCT.getAttr(),productArray);
        productData.put(BasicConstant.OFF_LINED_PRODUCTS,offlinedProducts);
    }

    @Override
    public void formatProduct4Show2(Long dataId, String corpid, JSONObject data, UpdateDataTypeEnum updateDataTypeEnum) throws XbbException {
        // 获取关联产品
        List<QuotationProductEntity> quoProductList = new ArrayList<>();
        if (Objects.isNull(dataId) || Objects.equals(dataId, 0L)) {
            if (data.get(QuotationEnum.PRODUCT.getAttr()) instanceof JSONObject) {
                JSONArray productArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(FastJsonHelper.getJsonObjectOrDefaultFromFormData(data, QuotationEnum.PRODUCT.getAttr(), new JSONObject()), StringConstant.PRODUCT_LIST, new JSONArray());
                Map<Long, ProductEntityExt> productMap = productModel.getProductMap(corpid, productArr);
                getProductList(corpid, quoProductList, productArr, productMap);
            } else {
                JSONArray jsonArray = data.getJSONArray(QuotationEnum.PRODUCT.getAttr());
                if (Objects.nonNull(jsonArray)) {
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        QuotationProductEntity quotationProductEntity = new QuotationProductEntity();
                        quotationProductEntity.setCorpid(corpid);
                        Long subProductId = FastJsonHelper.getLongFromFormData(jsonObject, BusinessConstant.PRODUCT_SUB_ID);
                        if (Objects.nonNull(subProductId)) {
                            quotationProductEntity.setId(subProductId);
                        }
                        quotationProductEntity.setProductId(jsonObject.getLong(SelectProductEnum.PRODUCT.getAttr()));
                        quotationProductEntity.setData(jsonObject);
                        quoProductList.add(quotationProductEntity);
                    }
                }
            }
        } else {
            // 检索del=0和del=6的数据，del=6是工作流中审批节点拒绝和撤回产生的数据，不是通过审批拒绝、撤回的数据不会产生del=6的数据，如果拒绝和撤回重新提交后，del=6将会被置回del=0
            quoProductList = quotationProductModel.getProductsByQuoId(dataId, corpid, Arrays.asList(DelEnum.NORMAL.getDel(), DelEnum.APPROVE_FAILED.getDel()));
        }
        formatProduct4Show3(quoProductList, data, updateDataTypeEnum, corpid);
    }

    @Override
    public Integer updateTime(Long id,String corpid) throws XbbException {
        long now = DateUtil.getInt();
        // 更新时间
        Integer success = quotationDao.updateTime(DateTimeUtil.getInt(), id, corpid);
        // 更新es
        PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
        paasFormDataEntity.setId(id);
        paasFormDataEntity.setDataId(id);
        paasFormDataEntity.setCorpid(corpid);
        paasFormDataEntity.setUpdateTime(now);
        InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_QUOTATION);
        paasEsModel.update(insertDTO);
        return success;
    }

    @Override
    public <T> List<T> getQuotationListByLinkId(String corpid, Long dataId, QuotationEnum quotationEnum, Class<T> clazz) throws XbbException {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termQuery(QuotationEnum.getEsAttr4Keyword(quotationEnum), dataId));
        // 最新的版本
        boolQueryBuilder.filter(termQuery(QuotationEnum.getEsAttr4Keyword(QuotationEnum.IS_NEW), BasicConstant.ONE));
        boolQueryBuilder.filter(termQuery("del", 0));
        boolQueryBuilder.filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(), FlowStatusEnum.PASS.getType())));
        boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, IndexTypeEnum.IDX_SAAS_QUOTATION.getType()));
        sourceBuilder.query(boolQueryBuilder);
        SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_QUOTATION.getIndex());
        PageRequest pageRequest = EsUtil.setPage(sourceBuilder, 0, PaasConstant.ES_MAX_PAGE_SIZE);
        searchRequest.source(sourceBuilder);
        XbbAggregatedPage<T> esEntities = xbbElasticsearchRestTemplate.queryForPages(pageRequest, searchRequest, clazz);
        return esEntities.getContent();
    }
}
